<template>
  <div id="appManagePage">
    <!-- 搜索表单 -->
    <div class="search-container">
      <div class="search-header">
        <div class="search-title">
          <span class="title-icon">🚀</span>
          <span>应用管理</span>
        </div>
        <div class="search-subtitle">管理系统中的所有应用程序</div>
      </div>
      <a-form layout="inline" :model="searchParams" @finish="doSearch" class="search-form">
        <a-form-item label="应用名称" class="form-item">
          <a-input
            v-model:value="searchParams.appName"
            placeholder="请输入应用名称"
            prefix="📱"
            class="search-input"
          />
        </a-form-item>
        <a-form-item label="创建者" class="form-item">
          <a-input
            v-model:value="searchParams.userId"
            placeholder="请输入用户ID"
            prefix="👤"
            class="search-input"
          />
        </a-form-item>
        <a-form-item label="生成类型" class="form-item">
          <a-select
            v-model:value="searchParams.codeGenType"
            placeholder="选择生成类型"
            style="width: 200px"
            class="search-select"
          >
            <a-select-option value="">全部</a-select-option>
            <a-select-option
              v-for="option in CODE_GEN_TYPE_OPTIONS"
              :key="option.value"
              :value="option.value"
            >
              {{ option.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item class="form-item">
          <a-button type="primary" html-type="submit" class="search-btn">
            <template #icon>
              <span>🔍</span>
            </template>
            搜索应用
          </a-button>
        </a-form-item>
      </a-form>
    </div>


    <!-- 表格容器 -->
    <div class="table-container">
      <a-table
        :columns="columns"
        :data-source="data"
        :pagination="pagination"
        @change="doTableChange"
        :scroll="{ x: 1200 }"
        class="app-table"
      >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'cover'">
          <a-image v-if="record.cover" :src="record.cover" :width="80" :height="60" />
          <div v-else class="no-cover">无封面</div>
        </template>
        <template v-else-if="column.dataIndex === 'initPrompt'">
          <a-tooltip :title="record.initPrompt">
            <div class="prompt-text">{{ record.initPrompt }}</div>
          </a-tooltip>
        </template>
        <template v-else-if="column.dataIndex === 'codeGenType'">
          {{ formatCodeGenType(record.codeGenType) }}
        </template>
        <template v-else-if="column.dataIndex === 'priority'">
          <a-tag v-if="record.priority === 99" color="gold">精选</a-tag>
          <span v-else>{{ record.priority || 0 }}</span>
        </template>
        <template v-else-if="column.dataIndex === 'deployedTime'">
          <span v-if="record.deployedTime">
            {{ dayjs(record.deployedTime).format('YYYY-MM-DD HH:mm:ss') }}
          </span>
          <span v-else class="text-gray">未部署</span>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.dataIndex === 'user'">
          <div class="user-info">
            <a-avatar :src="record.user?.userAvatar" size="small" />
            <span>{{ record.user?.userName || '未知用户' }}</span>
          </div>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="primary" size="small" @click="editApp(record)"> 编辑 </a-button>
            <a-button
              type="default"
              size="small"
              @click="toggleFeatured(record)"
              :class="{ 'featured-btn': record.priority === 99 }"
            >
              {{ record.priority === 99 ? '取消精选' : '精选' }}
            </a-button>
            <a-popconfirm title="确定要删除这个应用吗？" @confirm="deleteApp(record.id)">
              <a-button danger size="small">删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
      </a-table>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { listAppVoByPageByAdmin, deleteAppByAdmin, updateAppByAdmin } from '@/api/appController'
import { CODE_GEN_TYPE_OPTIONS, formatCodeGenType } from '@/utils/codeGenTypes'
import dayjs from 'dayjs'

const router = useRouter()

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80,
    fixed: 'left',
  },
  {
    title: '应用名称',
    dataIndex: 'appName',
    width: 150,
  },
  {
    title: '封面',
    dataIndex: 'cover',
    width: 100,
  },
  {
    title: '初始提示词',
    dataIndex: 'initPrompt',
    width: 200,
  },
  {
    title: '生成类型',
    dataIndex: 'codeGenType',
    width: 100,
  },
  {
    title: '优先级',
    dataIndex: 'priority',
    width: 80,
  },
  {
    title: '部署时间',
    dataIndex: 'deployedTime',
    width: 160,
  },
  {
    title: '创建者',
    dataIndex: 'user',
    width: 120,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 160,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
  },
]

// 数据
const data = ref<API.AppVO[]>([])
const total = ref(0)

// 搜索条件
const searchParams = reactive<API.AppQueryRequest>({
  pageNum: 1,
  pageSize: 10,
})

// 获取数据
const fetchData = async () => {
  try {
    const res = await listAppVoByPageByAdmin({
      ...searchParams,
    })
    if (res.data.data) {
      data.value = res.data.data.records ?? []
      total.value = res.data.data.total ?? 0
    } else {
      message.error('获取数据失败，' + res.data.message)
    }
  } catch (error) {
    console.error('获取数据失败：', error)
    message.error('获取数据失败')
  }
}

// 页面加载时请求一次
onMounted(() => {
  fetchData()
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.pageNum ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total: number) => `共 ${total} 条`,
  }
})

// 表格变化处理
const doTableChange = (page: { current: number; pageSize: number }) => {
  searchParams.pageNum = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

// 搜索
const doSearch = () => {
  // 重置页码
  searchParams.pageNum = 1
  fetchData()
}

// 编辑应用
const editApp = (app: API.AppVO) => {
  router.push(`/app/edit/${app.id}`)
}

// 切换精选状态
const toggleFeatured = async (app: API.AppVO) => {
  if (!app.id) return

  const newPriority = app.priority === 99 ? 0 : 99

  try {
    const res = await updateAppByAdmin({
      id: app.id,
      priority: newPriority,
    })

    if (res.data.code === 0) {
      message.success(newPriority === 99 ? '已设为精选' : '已取消精选')
      // 刷新数据
      fetchData()
    } else {
      message.error('操作失败：' + res.data.message)
    }
  } catch (error) {
    console.error('操作失败：', error)
    message.error('操作失败')
  }
}

// 删除应用
const deleteApp = async (id: number | undefined) => {
  if (!id) return

  try {
    const res = await deleteAppByAdmin({ id })
    if (res.data.code === 0) {
      message.success('删除成功')
      // 刷新数据
      fetchData()
    } else {
      message.error('删除失败：' + res.data.message)
    }
  } catch (error) {
    console.error('删除失败：', error)
    message.error('删除失败')
  }
}
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');

/* 统一动画变量 */
:root {
  --animation-duration-fast: 0.2s;
  --animation-duration-normal: 0.3s;
  --animation-duration-slow: 0.5s;
  --animation-easing: cubic-bezier(0.4, 0, 0.2, 1);
  --animation-easing-bounce: cubic-bezier(0.68, -0.55, 0.265, 1.55);
}

/* 动画定义 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideInLeft {
  from {
    opacity: 0;
    transform: translateX(-30px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

#appManagePage {
  padding: 32px;
  background: rgba(248, 250, 252, 0.8);
  min-height: 100vh;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  animation: fadeInUp 0.8s var(--animation-easing);
}

/* 搜索容器样式 */
.search-container {
  background: rgba(255, 255, 255, 0.98);
  border-radius: 20px;
  padding: 28px;
  margin-bottom: 24px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.08);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  animation: slideInLeft 0.6s var(--animation-easing);
  position: relative;
  overflow: hidden;
}

.search-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #f093fb 0%, #f5576c 50%, #4facfe 100%);
  border-radius: 20px 20px 0 0;
}

.search-header {
  text-align: center;
  margin-bottom: 24px;
}

.search-title {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  font-size: 22px;
  font-weight: 700;
  color: #1a202c;
  margin-bottom: 6px;
}

.title-icon {
  font-size: 24px;
}

.search-subtitle {
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
  opacity: 0.8;
}

.search-form {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 16px;
}

.form-item {
  margin-bottom: 0;
}

.search-input {
  width: 220px;
  height: 40px;
  border-radius: 12px;
  border: 2px solid rgba(226, 232, 240, 0.8);
  transition: all var(--animation-duration-normal) var(--animation-easing);
  font-weight: 500;
}

.search-input:hover {
  border-color: rgba(245, 87, 108, 0.4);
  box-shadow: 0 0 0 3px rgba(245, 87, 108, 0.05);
}

.search-input:focus {
  border-color: #f5576c;
  box-shadow: 0 0 0 3px rgba(245, 87, 108, 0.15);
}

.search-select {
  height: 40px;
  border-radius: 12px;
}

.search-btn {
  height: 40px;
  padding: 0 24px;
  border-radius: 12px;
  font-weight: 600;
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  border: none;
  box-shadow: 0 4px 15px rgba(245, 87, 108, 0.3);
  transition: all var(--animation-duration-normal) var(--animation-easing);
}

.search-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(245, 87, 108, 0.4);
  background: linear-gradient(135deg, #e879f9 0%, #ef4444 100%);
}

/* 表格容器样式 */
.table-container {
  background: rgba(255, 255, 255, 0.98);
  border-radius: 20px;
  padding: 24px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.08);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  animation: fadeInUp 0.6s var(--animation-easing) 0.2s both;
  position: relative;
  overflow: hidden;
}

.table-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #4facfe 0%, #00f2fe 50%, #43e97b 100%);
  border-radius: 20px 20px 0 0;
}

#appManagePage :deep(.ant-form) {
  background: rgba(255, 255, 255, 0.95);
  padding: 24px;
  border-radius: 16px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.08);
  margin-bottom: 24px;
  animation: slideInLeft 0.6s var(--animation-easing) 0.2s both;
}

#appManagePage :deep(.ant-form-item-label > label) {
  font-weight: 600;
  color: #374151;
}

#appManagePage :deep(.ant-input) {
  border-radius: 12px;
  border: 1px solid rgba(209, 213, 219, 0.8);
  transition: all var(--animation-duration-normal) var(--animation-easing);
}

#appManagePage :deep(.ant-input):focus {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

#appManagePage :deep(.ant-select) {
  border-radius: 12px;
}

#appManagePage :deep(.ant-select .ant-select-selector) {
  border-radius: 12px;
  border: 1px solid rgba(209, 213, 219, 0.8);
  transition: all var(--animation-duration-normal) var(--animation-easing);
}

#appManagePage :deep(.ant-btn-primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 12px;
  font-weight: 600;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
  transition: all var(--animation-duration-normal) var(--animation-easing);
}

#appManagePage :deep(.ant-btn-primary):hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}

.app-table {
  background: transparent;
  border-radius: 16px;
}

#appManagePage :deep(.ant-table) {
  background: transparent;
  border-radius: 16px;
}

#appManagePage :deep(.ant-table-thead > tr > th) {
  background: rgba(102, 126, 234, 0.05);
  border-bottom: 1px solid rgba(102, 126, 234, 0.1);
  font-weight: 600;
  color: #374151;
}

#appManagePage :deep(.ant-table-tbody > tr) {
  transition: all var(--animation-duration-normal) var(--animation-easing);
}

#appManagePage :deep(.ant-table-tbody > tr:hover) {
  background: rgba(102, 126, 234, 0.02);
  transform: translateX(2px);
}

#appManagePage :deep(.ant-table-tbody > tr > td) {
  vertical-align: middle;
  border-bottom: 1px solid rgba(229, 231, 235, 0.5);
}

#appManagePage :deep(.ant-divider) {
  border-color: rgba(102, 126, 234, 0.1);
  margin: 24px 0;
}

.no-cover {
  width: 80px;
  height: 60px;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #94a3b8;
  font-size: 12px;
  border-radius: 8px;
  border: 1px solid rgba(203, 213, 225, 0.5);
  transition: all var(--animation-duration-normal) var(--animation-easing);
}

.no-cover:hover {
  background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e1 100%);
  color: #64748b;
}

.prompt-text {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #4b5563;
  font-weight: 500;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.text-gray {
  color: #6b7280;
  font-weight: 500;
}

.featured-btn {
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
  border: none;
  border-radius: 8px;
  color: white;
  font-weight: 600;
  box-shadow: 0 4px 15px rgba(245, 158, 11, 0.3);
  transition: all var(--animation-duration-normal) var(--animation-easing);
}

.featured-btn:hover {
  background: linear-gradient(135deg, #d97706 0%, #b45309 100%);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(245, 158, 11, 0.4);
}

#appManagePage :deep(.ant-btn) {
  border-radius: 8px;
  font-weight: 500;
  transition: all var(--animation-duration-normal) var(--animation-easing);
}

#appManagePage :deep(.ant-btn:hover) {
  transform: translateY(-1px);
}

#appManagePage :deep(.ant-btn-dangerous) {
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  border: none;
  color: white;
  box-shadow: 0 4px 15px rgba(239, 68, 68, 0.3);
}

#appManagePage :deep(.ant-btn-dangerous):hover {
  background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
  box-shadow: 0 6px 20px rgba(239, 68, 68, 0.4);
}

/* 响应式设计 */
@media (max-width: 768px) {
  #appManagePage {
    padding: 20px 16px;
  }

  #appManagePage :deep(.ant-form) {
    padding: 16px;
  }
}
</style>
